package com.dsp.adx.util.timer;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;



import org.apache.log4j.Logger;

import com.dsp.adx.annotation.QuartzTime;


public class TimeUtil {
	
	private static Logger log = Logger.getLogger(TimeUtil.class);
	
	private static ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
	
	public static void startJob(final Class clazz){
		Method [] methods = clazz.getDeclaredMethods();
    	for (final Method m : methods) {
			if(m.isAnnotationPresent(QuartzTime.class)){
				QuartzTime qt = m.getAnnotation(QuartzTime.class);  
	    		if (qt != null) {
	    			Runnable r = new Runnable() {  
	    	            public void run() {  
	    	            	try {
								m.invoke(clazz.newInstance());
							} catch (IllegalAccessException
									| IllegalArgumentException
									| InvocationTargetException
									| InstantiationException e) {
								e.printStackTrace();
							}
	    	            }  
	    	        };
	    	        log.info("创建作业=> [作业方法：" +clazz.getName() +"."+ m.getName() + "()] ");
	    	        service.scheduleAtFixedRate(r, 0, qt.delayTime(), qt.unit()); 
				}
			}
		}
	}
	
	@QuartzTime(delayTime = 2)
	public void test(){
		System.out.println("执行了！");
	}
	
	@QuartzTime(delayTime = 2)
	public void test1(){
		System.out.println("执行第二个了！");
	}
	
	
	public static void main(String[] args) {
		TimeUtil tu = new TimeUtil();
		tu.startJob(TimeUtil.class);
	}
}
